package models

import (
	"errors"
	"fmt"
	"github.com/astaxie/beego/orm"
	"sort"
	"time"
)

/* table_name = company */
type Company struct {
	Id              int       `orm:"auto;pk"`                     // 企业编号
	Name            string    `description:"企业名称"`                // 企业名称
	Type            int       `description:"企业标签"`                // 企业标签
	Rank            int       `description:"企业排行"`                // 企业排行
	Property        int       `description:"企业属性"`                // 企业属性
	Category        int       `description:"行业标签"`                // 行业标签
	Location        string    `description:"企业地点"`                // 企业地点
	Information     string    `description:"企业信息"`                // 企业信息
	Address         string    `description:"企业地址"`                // 企业地址
	Website         string    `description:"企业官网"`                // 企业官网
	OfficialAccount string    `description:"企业公众号"`               // 企业公众号
	Status          bool      `description:"当前状态"`                // 当前状态
	Size            int       `description:"企业规模"`                //企业规模(0:0-200;1:200-500;2:500-100;3:1000-5000;4:5000人以上)
	CreateTime      time.Time `orm:"auto_now_add;type(datetime)"` // 注册时间
	//UserCompanyBrowseId *UserCompanyBrowse    `orm:"reverse(many)" json:"user_company_browse_id"`   	// 企业浏览记录
	Descriptions []*CompanyDescription `orm:"reverse(many)"` // 企业描述
	Account      []*CompanyAccount     `orm:"reverse(many)"` // 企业描述
	Job          []*CompanyJob         `orm:"reverse(many)"` // 企业职位
	Live         *Live                 `orm:"reverse(one)"`  //企业直播
	//Interviews          []*CompanyInterview   `orm:"reverse(many)" json:"company_interview"`          // 企业邀请的面试
}

/* table_name = company_account */
type CompanyAccount struct {
	Id         int `orm:"auto;pk"`
	Username   string
	Password   string
	Company    *Company `orm:"rel(fk)" json:"-"`
	Type       int
	Status     bool
	CreateTime time.Time `orm:"auto_now_add;type(datetime)"`
}

/* table_name = company_description */
type CompanyDescription struct {
	Id          int `orm:"auto;pk"`
	Title       string
	Description string
	Url         string
	Type        bool      `description:"0-图片 1-视频"`
	Company     *Company  `orm:"rel(fk)" json:"-"`
	Status      bool      `json:"status"`
	CreateTime  time.Time `orm:"auto_now_add;type(datetime)"`
}

/* table_name = company_job */
type CompanyJob struct {
	Id             int
	Name           string
	NameFirst      string
	NameSecond     string
	Condition      string //岗位条件
	Responsibility string
	Development    string
	Province       string
	City           string
	Area           string
	Major          string
	SchoolRank     int
	Education      int
	EducationType  int
	SalaryMax      int  //薪酬上限
	SalaryMin      int  //薪酬下限
	Type           bool //岗位类型
	Welfare        string
	Num            int
	Note           string
	Company        *Company  `orm:"rel(fk)" json:"-"`
	Status         bool      // 当前状态
	CreateTime     time.Time `orm:"auto_now_add;type(datetime)"` // 注册时间
}

/* table_name = company_interview */
type CompanyInterview struct {
	Id         int
	Note       string
	User       *User       `orm:"rel(fk)" json:"user"`
	Company    *Company    `orm:"rel(fk)"`
	CompanyJob *CompanyJob `orm:"rel(fk)"`
	Result     int         `json:"result"`
	ResultType int
	IsPayed    bool
	Status     bool      `json:"company_status"`                                // 当前状态
	CreateTime time.Time `orm:"auto_now_add;type(datetime)" json:"create_time"` // 注册时间
}

/* table_name = welfare */
type Welfare struct {
	Id         int
	Name       string
	Status     bool
	Type       int
	CreateTime time.Time `orm:"auto_now_add;type(datetime)"` // 注册时间
}

/* 用于查看已发布岗位招聘情况 */
type JobInterviewWithArea struct {
	Id       int
	Name     string
	CityName string
	All      int
	Single   int
	Double   int
	Offer    int
	Num      int
	Note     string
}

type UserWithResume struct {
	Id        int
	User      *User
	Recommend int
	Elite     int
	Note      string
	Type      int `description:"0:用户投简历 1:公司邀请"`
}

type CompanyStar struct {
	Company *Company
	IsStar  bool
}

type UserWithResumes []UserWithResume

func (s UserWithResumes) Len() int { return len(s) }

func (s UserWithResumes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func (s UserWithResumes) Less(i, j int) bool { return s[i].Recommend > s[j].Recommend }

// static data
func GetWelfareList() ([]*Welfare, error) {
	var wel []*Welfare
	_, err := O.QueryTable("welfare").Filter("status", 1).All(&wel)
	return wel, err
}

// Company operate
func AddCompany(company *Company) error {
	_, err := O.Insert(company)
	return err
}

func UpdateCompany(company *Company) error {
	_, err := O.Update(company)
	return err
}

func GetCompanyById(id int) (*Company, error) {
	c := Company{Id: id}
	err := O.Read(&c, "id")
	return &c, err
}

func GetCompanyByName(name string) (*Company, error) {
	c := Company{Name: name}
	err := O.Read(&c, "name")
	return &c, err
}

func GetCompanyList(page int, limit int) ([]*Company, error) {
	var c []*Company
	_, err := O.QueryTable("company").Filter("status", 1).Limit(limit, page*limit).All(&c)
	return c, err
}

func GetCompanyListByCondition(jobList []string, locationList []string, jobType int, salaryMax int, salaryMin int, welfareList []string, typeList []int, rankList []int,
	size int, categoryList []int, order int,
	page int, limit int) ([]*Company, error) {
	var c []*Company

	qs := O.QueryTable("company")
	if jobList != nil {
		cond := orm.NewCondition()
		for _, i := range jobList {
			cond = cond.Or("Job__Name__contains", i)
			cond = cond.Or("Job__NameFirst__contains", i)
			cond = cond.Or("Job__NameSecond__contains", i)
		}
		qs = qs.SetCond(cond).Filter("Job__status", 1).Distinct()
		//qs = qs.Filter("Job__Name__in", jobList).Filter("Job__status", 1).Distinct()
	}
	if locationList != nil {
		qs = qs.Filter("Location__in", locationList)
	}
	if jobType != -1 {
		qs = qs.Filter("Job__Type", jobType).Filter("Job__status", 1).Distinct()
	}
	if salaryMax != -1 && salaryMin != -1 {
		qs = qs.Filter("Job__SalaryMax__lte", salaryMax).Filter("Job__SalaryMax__gte", salaryMin).Distinct()
	}
	if welfareList != nil {
		cond := orm.NewCondition()
		for _, i := range welfareList {
			cond = cond.Or("Job__Welfare__contains", i)
		}
		qs = qs.SetCond(cond)
	}
	if typeList != nil {
		qs = qs.Filter("type__in", typeList)
	}
	if rankList != nil {
		qs = qs.Filter("rank__in", rankList)
	}
	if size != -1 {
		qs = qs.Filter("size", size)
	}
	if categoryList != nil {
		qs = qs.Filter("category__in", categoryList)
	}
	switch order {
	case -1:
		break
	case 0:
		qs = qs.OrderBy("Category")
	case 1:
		qs = qs.OrderBy("Location")
	case 2:
		qs = qs.OrderBy("Live__Status")
	case 3:
		qs = qs.OrderBy("Size")
	case 4:
		qs = qs.OrderBy("Job__SalaryMin")
	case 5:
		qs = qs.OrderBy("Job__Name")
	}
	_, err := qs.Filter("status", 1).Limit(limit, page*limit).All(&c)
	return c, err
}

func GetCompanyListByKeyword(keyword string, page int, limit int) ([]*Company, error) {
	var c []*Company
	cond := orm.NewCondition().
		Or("name__icontains", keyword).
		Or("location__icontains", keyword).
		Or("information__icontains", keyword).
		Or("address__icontains", keyword).
		Or("website__icontains", keyword).
		Or("official_account__icontains", keyword)
	_, err := O.QueryTable("company").
		Filter("status", 1).
		SetCond(cond).
		Limit(limit, page*limit).All(&c)
	return c, err
}

// Company description operate
func AddCompanyDescription(description *CompanyDescription) error {
	_, err := O.Insert(description)
	return err
}

func GetCompanyDescriptionByCompanyId(id int) ([]*CompanyDescription, error) {
	var c []*CompanyDescription
	_, err := O.QueryTable("company_description").Filter("status", 1).Filter("company_id", id).All(&c)
	return c, err
}

// Company job operate
func AddCompanyJob(job *CompanyJob) error {
	_, err := O.Insert(job)
	return err
}

func GetCompanyJobByCompanyId(id int) ([]*CompanyJob, error) {
	var c []*CompanyJob
	_, err := O.QueryTable("company_job").Filter("status", 1).Filter("company_id", id).All(&c)
	return c, err
}

func GetCompanyJobById(id int) (*CompanyJob, error) {
	var c = CompanyJob{
		Id: id,
	}
	err := O.Read(&c)
	return &c, err
}

func GetCompanyListJob(cList []*Company) ([]*Company, error) {
	var c *Company
	for _, c = range cList {
		var cj []*CompanyJob
		_, err := O.QueryTable("company_job").Filter("status", 1).Filter("company_id", c.Id).All(&cj)
		if err != nil {
			print(err.Error())
			return cList, err
		}
		c.Job = cj
	}
	return cList, nil
}

func UpdateCompanyJob(job *CompanyJob) error {
	_, err := O.Update(job)
	return err
}

func UpdateCompanyJobNote(job *CompanyJob) error {
	_, err := O.Update(
		job,
		"note")
	return err
}

func UpdateCompanyInterviewByCompany(interview CompanyInterview) error {
	var dbInterview CompanyInterview
	_ = O.QueryTable("company_interview").
		Filter("Id", interview.Id).
		One(&dbInterview)
	// 公司同意用户简历 - 简历进入下一轮
	if interview.ResultType == 1 && interview.Result != 4 {
		interview.Result = dbInterview.Result + 1
		interview.ResultType = 2
	}
	_, err := O.Update(&interview,
		"result",
		"result_type")

	return err
}

func UpdateInterviewOrResumeNote(id int, note string, t int) error {
	var err error
	if t == 0 {
		var userResumePut UserResumePut
		_ = O.QueryTable("user_resume_put").
			Filter("id", id).Filter("status", 1).
			One(&userResumePut)
		userResumePut.Note = note
		_, err = O.Update(&userResumePut,
			"note")
		return err
	} else if t == 1 {
		var companyInterview CompanyInterview
		_ = O.QueryTable("company_interview").
			Filter("id", id).Filter("status", 1).
			One(&companyInterview)
		companyInterview.Note = note
		_, err = O.Update(&companyInterview,
			"note")
		return err
	} else {
		// TODO: Unknown error
		return errors.New("")
	}
}

// Company live operate
func GetCompanyListLive(cList []*Company) ([]*Company, error) {
	var c *Company
	for _, c = range cList {
		var l Live
		err := O.QueryTable("live").Filter("status", 1).Filter("company_id", c.Id).One(&l)
		//err := O.Read(c.Live)
		if err == orm.ErrMultiRows {
			// 多条的时候报错
			fmt.Printf("Returned Multi Rows Not One")
		}
		if err == orm.ErrNoRows {
			// 没有找到记录
			fmt.Printf("Not row found")
		}
		c.Live = &l
	}
	return cList, nil
}

// Company star operate
func GetCompanyListStar(cList []*Company, userId int) []*CompanyStar {

	var slist []*CompanyStar
	for _, c := range cList {
		isStar := getIsUserStarCompany(userId, c.Id)
		var cs = new(CompanyStar)
		cs.IsStar = isStar
		cs.Company = c
		slist = append(slist, cs)
	}
	return slist
}

// Company account operate
func CompanyLogin(account *CompanyAccount) (*CompanyAccount, error) {
	err := O.Read(account, "username", "password", "status")
	return account, err
}

func CompanyAccountCheck(account *CompanyAccount) (*CompanyAccount, error) {
	err := O.Read(account, "username")
	return account, err
}

func CompanyRegister(account *CompanyAccount) error {
	_, err := O.Insert(account)
	return err
}

func GetCompanyAccountById(id int) (*CompanyAccount, error) {
	c := CompanyAccount{Id: id}
	err := O.Read(&c, "id")
	return &c, err
}

func UpdateCompanyAccount(account *CompanyAccount) error {
	_, err := O.Update(account)
	return err
}

// web api
/*
 获取公司面试情况
*/
func GetCompanyInterviewWithNumById(companyId int, page int, limit int) ([]JobInterviewWithArea, error) {
	var jobs []*CompanyJob
	var jobInterviewInfos []JobInterviewWithArea

	_, err := O.QueryTable("company_job").
		Filter("status", 1).Filter("company_id", companyId).
		Limit(limit, page*limit).
		All(&jobs)
	if err != nil {
		return nil, errors.New("ContentIsNull")
	}

	for _, job := range jobs {
		var jobInterviewInfo JobInterviewWithArea
		jobInterviewInfo.Id = job.Id
		jobInterviewInfo.Name = job.Name
		jobInterviewInfo.Single, err = getJobInterviewNum(job, 1)
		jobInterviewInfo.Double, err = getJobInterviewNum(job, 2)
		jobInterviewInfo.Offer, err = getJobInterviewNum(job, 3)

		jobInterviewInfos = append(jobInterviewInfos, jobInterviewInfo)
	}

	return jobInterviewInfos, err
}

/*
 更新公司介绍
*/
func UpdateCompanyDesc(company Company) error {
	_, err := O.Update(&company,
		"Name",
		"Address",
		"Type",
		"Size",
		"Category",
	)

	return err
}

/*
 获取指定岗位的各地区分配
*/
func GetEmployInformationByJobName(jobName string, companyId int, page int, limit int, keyword string) ([]JobInterviewWithArea, error) {
	var jobs []*CompanyJob
	var jobInterviews []JobInterviewWithArea

	if keyword != "" {
		cond := orm.NewCondition().
			Or("name__icontains", keyword).
			Or("condition__icontains", keyword).
			Or("responsibility__icontains", keyword).
			Or("development__icontains", keyword).
			Or("province__icontains", keyword).
			Or("city__icontains", keyword).
			Or("area__icontains", keyword).
			Or("compensation__icontains", keyword).
			Or("welfare__icontains", keyword).
			Or("num__icontains", keyword)
		_, err := O.QueryTable("company_job").
			SetCond(cond).
			Filter("status", 1).Filter("name", jobName).Filter("company_id", companyId).
			Limit(limit, page).
			All(&jobs)
		if err != nil {

		}
	} else {
		_, err := O.QueryTable("company_job").
			Filter("status", 1).Filter("name", jobName).Filter("company_id", companyId).
			Limit(limit, page).
			All(&jobs)
		if err != nil {

		}
	}

	for _, job := range jobs {
		jobInterview, err := getJobWithNum(job)
		if err != nil {
			return nil, errors.New("")
		}

		jobInterviews = append(jobInterviews, jobInterview)
	}

	return jobInterviews, nil
}

/*
 获取指定地点，指定岗位，指定类型的招聘信息
*/
func GetUserInformationByJobName(name string, city string, t int, companyId int, page int, limit int, keyword string) ([]UserWithResume, error) {
	var job CompanyJob
	var user User
	var users []*User
	var userWithResumes []UserWithResume
	var companyInterviews []*CompanyInterview
	var userResumePuts []*UserResumePut
	var cond *orm.Condition

	err := O.QueryTable("company_job").
		Filter("status", 1).Filter("name", name).Filter("city", city).Filter("company_id", companyId).
		One(&job)
	if err != nil {
	}
	if keyword != "" {
		cond = orm.NewCondition().
			Or("username__icontains", keyword).
			Or("nickname__icontains", keyword).
			Or("city__icontains", keyword).
			Or("province__icontains", keyword).
			Or("area__icontains", keyword).
			Or("real_name__icontains", keyword).
			Or("hobby1__icontains", keyword).
			Or("hobby2__icontains", keyword).
			Or("hobby3__icontains", keyword).
			Or("department__icontains", keyword).
			Or("position__icontains", keyword).
			Or("university__icontains", keyword).
			Or("email__icontains", keyword)
	}

	if t == 0 {
		_, err = O.QueryTable("user").
			Filter("status", 1).Limit(limit, page).
			SetCond(cond).
			All(&users)
		for _, u := range users {
			userWithResume := UserWithResume{User: u}
			userWithResumes = append(userWithResumes, userWithResume)
		}
		return userWithResumes, err
	} else if t == 1 {
		_, err = O.QueryTable("company_interview").
			Filter("status", 1).Filter("company_job_id", job.Id).Filter("result_type__gt", 0).Filter("result__lt", 4).
			All(&companyInterviews)
		if err != nil {
		}
		for _, companyInterview := range companyInterviews {
			err = O.QueryTable("user").
				Filter("status", 1).Filter("id", companyInterview.User.Id).
				SetCond(cond).
				One(&user)
			userWithResume := UserWithResume{Id: companyInterview.Id, User: &user, Note: companyInterview.Note, Type: 1}
			userWithResumes = append(userWithResumes, userWithResume)
		}
		_, err = O.QueryTable("user_resume_put").
			Filter("status", 1).Filter("result_type", 2).Filter("job_id", job.Id).Filter("result__lt", 4).
			All(&userResumePuts)
		if err != nil {
		}
		for _, userResumePut := range userResumePuts {
			err = O.QueryTable("user").
				Filter("status", 1).Filter("id", userResumePut.User.Id).
				SetCond(cond).
				One(&user)
			userWithResume := UserWithResume{Id: userResumePut.Id, User: &user, Note: userResumePut.Note, Type: 0}
			userWithResumes = append(userWithResumes, userWithResume)
		}
	} else if t == 2 {
		_, err = O.QueryTable("company_interview").
			Filter("status", 1).Filter("company_job_id", job.Id).Filter("result_type", 1).Filter("result__lt", 4).
			All(&companyInterviews)
		if err != nil {
		}
		for _, companyInterview := range companyInterviews {
			err = O.QueryTable("user").
				Filter("status", 1).Filter("id", companyInterview.User.Id).
				SetCond(cond).
				One(&user)
			userWithResume := UserWithResume{Id: companyInterview.Id, User: &user, Note: companyInterview.Note, Type: 1}
			userWithResumes = append(userWithResumes, userWithResume)
		}
		_, err = O.QueryTable("user_resume_put").
			Filter("status", 1).Filter("result_type", 1).Filter("job_id", job.Id).Filter("result__lt", 4).
			All(&userResumePuts)
		if err != nil {
		}
		for _, userResumePut := range userResumePuts {
			err = O.QueryTable("user").
				Filter("status", 1).Filter("id", userResumePut.User.Id).
				SetCond(cond).
				One(&user)
			userWithResume := UserWithResume{Id: userResumePut.Id, User: &user, Note: userResumePut.Note, Type: 0}
			userWithResumes = append(userWithResumes, userWithResume)
		}
	} else if t == 3 {
		_, err = O.QueryTable("company_interview").
			Filter("status", 1).Filter("company_job_id", job.Id).Filter("result_type", 1).Filter("result", 4).
			All(&companyInterviews)
		if err != nil {
		}
		for _, companyInterview := range companyInterviews {
			err = O.QueryTable("user").
				Filter("status", 1).Filter("id", companyInterview.User.Id).
				SetCond(cond).
				One(&user)
			userWithResume := UserWithResume{Id: companyInterview.Id, User: &user, Note: companyInterview.Note, Type: 1}
			userWithResumes = append(userWithResumes, userWithResume)
		}
		_, err = O.QueryTable("user_resume_put").
			Filter("status", 1).Filter("result_type", 1).Filter("job_id", job.Id).Filter("result", 4).
			All(&userResumePuts)
		if err != nil {
		}
		for _, userResumePut := range userResumePuts {
			err = O.QueryTable("user").
				Filter("status", 1).Filter("id", userResumePut.User.Id).
				SetCond(cond).
				One(&user)
			userWithResume := UserWithResume{Id: userResumePut.Id, User: &user, Note: userResumePut.Note, Type: 0}
			userWithResumes = append(userWithResumes, userWithResume)
		}
	}

	if len(users) < page {
		return nil, err
	}
	if len(users) < page+limit {
		return userWithResumes[page:], err
	}
	return userWithResumes[page : page+limit], err
}

/*

 */
func GetEmployGroupByJobName(companyId int, page int, limit int, keyword string) ([]JobInterviewWithArea, error) {
	var companyJobs []*CompanyJob
	var jobs []JobInterviewWithArea

	if keyword != "" {
		cond := orm.NewCondition().
			Or("name__icontains", keyword).
			Or("location__icontains", keyword).
			Or("information__icontains", keyword).
			Or("address__icontains", keyword).
			Or("website__icontains", keyword).
			Or("official_account__icontains", keyword)
		_, err := O.QueryTable("company_job").
			Filter("status", 1).Filter("company_id", companyId).
			SetCond(cond).
			GroupBy("name").
			Limit(limit, page).
			All(&companyJobs, "name")
		if err != nil {
			return nil, err
		}
	} else {
		_, err := O.QueryTable("company_job").
			Filter("status", 1).Filter("company_id", companyId).
			GroupBy("name").
			Limit(limit, page).
			All(&companyJobs, "name")
		if err != nil {
			return nil, err
		}
	}

	for _, job := range companyJobs {
		var jobIds []*CompanyJob
		jobInterview := JobInterviewWithArea{
			Id:     0,
			Name:   job.Name,
			All:    0,
			Single: 0,
			Double: 0,
			Offer:  0,
			Num:    0,
		}
		_, err := O.QueryTable("company_job").
			Filter("company_id", companyId).Filter("name", job.Name).Filter("status", 1).
			All(&jobIds)
		if err != nil {
			return nil, err
		}

		for _, jobId := range jobIds {
			tmpJobInterview, err := getJobWithNum(jobId)
			if err != nil {
				return nil, errors.New("")
			}
			jobInterview.Id += tmpJobInterview.Id
			jobInterview.All += tmpJobInterview.All
			jobInterview.Single += tmpJobInterview.Single
			jobInterview.Double += tmpJobInterview.Double
			jobInterview.Offer += tmpJobInterview.Offer
			jobInterview.Num += tmpJobInterview.Num
		}

		jobs = append(jobs, jobInterview)
	}

	return jobs, nil
}

func GetEmployNum(companyId int) (int, int, error) {
	var jobs []*CompanyJob
	allNum := 0

	jobNum, err := O.QueryTable("company_job").
		Filter("status", 1).Filter("company_id", companyId).
		GroupBy("name").
		Count()
	_, _ = O.QueryTable("company_job").
		Filter("status", 1).Filter("company_id", companyId).
		All(&jobs)
	for _, job := range jobs {
		allNum += job.Num
	}

	return int(jobNum), allNum, err
}

/*

 */
func GetRecommend(jobId int) ([]UserWithResume, error) {
	var users []*User
	var job CompanyJob
	var userWithResumes UserWithResumes

	err := O.QueryTable("company_job").
		Filter("status", 1).Filter("id", jobId).
		One(&job)
	if err != nil {
		return nil, errors.New("JobNotExist")
	}
	_, err = O.QueryTable("user").
		Filter("status", 1).
		All(&users)

	// 计算 推荐指数

	sort.Sort(userWithResumes)

	return userWithResumes, err
}

/*
 公司: 查找 指定类型 用户投放/公司邀请
 若 type -1: 全部 1: 单向 2: 双向
*/
func QueryAllUserPutAndCompanyInviteByCompany(companyId int, t int, page int, limit int) ([]*UserPutAndCompanyInvite, error) {
	var putAndInvite []*UserPutAndCompanyInvite
	var err error

	if t == -1 {
		_, err = O.QueryTable("user_put_and_company_invite").
			Filter("status", 1).Filter("company_id", companyId).
			Limit(limit, page).
			All(&putAndInvite)
	} else if t == 0 {
		_, err = O.QueryTable("user_put_and_company_invite").
			Filter("status", 1).Filter("company_id", companyId).Filter("offer", 0).
			Limit(limit, page).
			All(&putAndInvite)
	} else if t == 1 {
		_, _ = O.Raw("SELECT * FROM `user_put_and_company_invite` WHERE `status`=1 AND ((`user_answer`=1 AND `company_answer`=2) OR (`user_answer`=2 AND `company_answer`=1)) AND `offer`=3 AND `company_id`=? LIMIT ?,?", companyId, page, limit).QueryRows(&putAndInvite)
	} else if t == 2 {
		_, err = O.QueryTable("user_put_and_company_invite").
			Filter("status", 1).Filter("company_id", companyId).Filter("offer", 3).Filter("user_answer", 1).Filter("company_answer", 1).
			Limit(limit, page).
			All(&putAndInvite)
	} else if t == 3 {
		_, err = O.QueryTable("user_put_and_company_invite").
			Filter("status", 1).Filter("company_id", companyId).Filter("offer", 1).
			Limit(limit, page).
			All(&putAndInvite)
	}

	return putAndInvite, err
}

// 获取职位名
func getCompanyJobName(jobId int) (string, error) {
	var companyJob CompanyJob

	err := O.QueryTable("company_job").
		Filter("status", 1).Filter("id", jobId).
		One(&companyJob)

	return companyJob.Name, err
}

// 获取公司面试岗位
func getCompanyInterviewById(companyId int) ([]*CompanyInterview, error) {
	var companyInterviews []*CompanyInterview

	_, err := O.QueryTable("company_interview").
		Filter("status", 1).Filter("company_id", companyId).
		All(&companyInterviews)
	return companyInterviews, err
}

// 获取岗位对应的面试人数
func getJobInterviewNum(job *CompanyJob, result int) (int, error) {
	num, err := O.QueryTable("company_interview").
		Filter("status", 1).Filter("result", result).
		Count()

	return int(num), err
}

// 计算 海选, 单选, 双选, offer 人数
func getJobWithNum(job *CompanyJob) (JobInterviewWithArea, error) {
	var jobInterview JobInterviewWithArea

	jobInterview.Id = job.Id
	jobInterview.CityName = job.City
	jobInterview.Name = job.Name

	// 获取海选
	jobInterview.All = 0 // TODO

	// 获取单向
	firstOfCompanyInterview, err := O.QueryTable("company_interview").
		Filter("status", 1).Filter("company_job_id", job.Id).Filter("result_type", 2).Filter("result__lt", 4).
		Count()
	if err != nil {
	}
	firstOfUserResumePut, err := O.QueryTable("user_resume_put").
		Filter("status", 1).Filter("result_type", 2).Filter("job_id", job.Id).Filter("result__lt", 4).
		Count()
	if err != nil {
	}
	jobInterview.Single = int(firstOfCompanyInterview + firstOfUserResumePut)

	// 获取双向
	secondOfCompanyInterview, err := O.QueryTable("company_interview").
		Filter("status", 1).Filter("company_job_id", job.Id).Filter("result_type", 1).Filter("result__lt", 4).
		Count()
	if err != nil {
	}
	secondOfUserResumePut, err := O.QueryTable("user_resume_put").
		Filter("status", 1).Filter("result_type", 1).Filter("job_id", job.Id).Filter("result__lt", 4).
		Count()
	if err != nil {
	}
	jobInterview.Double = int(secondOfCompanyInterview + secondOfUserResumePut)

	// 获取 offer
	offerOfCompanyInterview, err := O.QueryTable("company_interview").
		Filter("status", 1).Filter("company_job_id", job.Id).Filter("result_type", 1).Filter("result", 4).
		Count()
	if err != nil {
	}
	offerOfUserResumePut, err := O.QueryTable("user_resume_put").
		Filter("status", 1).Filter("result_type", 1).Filter("job_id", job.Id).Filter("result", 4).
		Count()
	if err != nil {
	}
	jobInterview.Offer = int(offerOfCompanyInterview + offerOfUserResumePut)

	jobInterview.Num = job.Num
	jobInterview.Note = job.Note

	return jobInterview, err
}

func getIsUserStarCompany(userId int, companyId int) bool {
	num, err := O.QueryTable("user_star_company").
		Filter("status", 1).Filter("user_id", userId).Filter("company_id", companyId).
		Count()

	if err != nil || num == 0 {
		return false
	}
	return true
}
